<?php

// +----------------------------------------------------------------------
// | Chnxu
// +----------------------------------------------------------------------

declare (strict_types=1);

namespace app\databackup\controller;

use think\admin\Controller;
use think\facade\Db;
use think\facade\Config;

class Databackup extends Controller
{
    protected $config = null;

    /**
     * 控制器初始化
     */
    protected function initialize()
    {
        $this->config = Config::get('databackup');
        if (!is_dir($this->config['path'])) {
            mkdir($this->config['path'], 0755, true);
        }
    }

    /**
     * 数据库备份
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $this->title = '数据库备份';
        $this->_scanBackupFiles();
        $this->fetch();
    }

    /**
     * 扫描备份文件
     */
    private function _scanBackupFiles() {
        $files = [];
        $items = scandir($this->config['path']);

        foreach ($items as $item) {
            if ($item === '.' || $item === '..') {
                continue;
            }

            $path = $this->config['path'] . '/' . $item;
            if (!is_file($path)) continue;
            $name = basename($path);
            $time = filectime($path);
            $size = filesize($path);
            $files[] = [
                'name'          => $name,
                'time'          => $time,
                'time_text'     => date('Y-m-d H:i:s', $time),
                'size'          => format_bytes($size),
                'path'          => $path
            ];
        }
        usort($files, function($a, $b) {
            return $b['time'] <=> $a['time'];
        });
        $this->list = $files;
    }

    /**
     * 备份操作
     * @auth true
     */
    public function backup()
    {
        sysoplog('数据库备份', '创建数据库备份任务');
        $this->_queue('创建数据库备份', "chnxu:databackup");
    }

    /**
     * 删除备份
     * @auth true
     */
    public function delete($name) {
        $params = $this->_vali([
            'path.require' => '参数错误',
        ]);
        if (is_dir($params['path'])) {
            $this->_deleteDir($params['path']);
            $this->success('备份删除成功');
        } else {
            $this->error('备份不存在');
        }
    }

    /**
     * 删除文件
     *
     * @param string $dir 删除的目录
     * @return bool
     */
    private function _deleteDir(string $dir): bool
    {
        $files = array_diff(scandir($dir), ['.','..']);
        foreach ($files as $file) {
            $path = $dir.'/'.$file;
            is_dir($path) ? $this->_deleteDir($path) : unlink($path);
        }
        return rmdir($dir);
    }
}